package main.java;
import java.awt.*;
import java.util.ArrayList;
import java.util.prefs.BackingStoreException;

/**
 * Created by dse on 12/14/2014.
 * TrinhNX 1221: Nothing to do :?
 * Rut kinh nghiem lan sau, ko comment lan nay.
 */
public class Bacteria {
    private static final int MAX_AGE = 5;
    private static final int COLOR_STEP = 256/MAX_AGE;
    private final Board board;

    private int age; // age of the creature measures in ticks
    private int x; // (x,y) is the position of the creature
    private int y;

    Bacteria(Board board, int _x, int _y) {
        this.board = board;
        //initialize age, x, y
        this.x = _x;
        this.y = _y; 
    }

    //Draw a circle representing the creature at its position
    //This function is done.
    public void draw(Graphics g) {
        g.setColor(new Color(0, COLOR_STEP * age, 0));
        g.fillOval(x * board.CELL_SIZE, y * board.CELL_SIZE, board.CELL_SIZE, board.CELL_SIZE);
    }

    public void tick() {
        //your code
        // this is how the creature lives in one tick
        // make the creature get older if it is not dead.
        // if it's got older than MAX_AGE then it should die
        // ...call board.addDead() to register the dead creature
        // if it can have baby then try reproduce()
    	age = age + 1;
    	if (age > MAX_AGE) {
    		board.addDead(this);
    	}  
    	if (canHaveBaby()) {
    		reproduce();
    	}
    	
     }

    public void reproduce() {
        //your code
        // if it can have a baby then produce a baby
        // ...in an empty cell next to its cell.
        // board.emptyCell() should be used
        // ....to check whether a cell in the board is empty
        // and call board.addBaby() to place the baby to the board
    	
    	if (board.emptyCell(x+1, y)) {
    		board.addBaby(new Bacteria(this.board, x+1, y));
    	}else if (board.emptyCell(x-1, y)) {
    		board.addBaby(new Bacteria(this.board, x-1, y));
    	}else if (board.emptyCell(x, y-1)) {
    		board.addBaby(new Bacteria(this.board, x, y-1));
    	}else if (board.emptyCell(x, y+1)) {
    		board.addBaby(new Bacteria(this.board, x, y-1));
    	} 
    }

    private boolean canHaveBaby() {
        //your code
        // if the creature is dead or it is too young
        // then it cannot have a baby
    	if (age > MAX_AGE && age <= 1) {
    		return false;
    	}
        return true;
    }

    public boolean atPosition(int _x, int _y) {
        //your code
        // return true if the creature is at the position (_x,_y)
        // you need this function for board.empty to function correctly
    	if (this.x == _x && this.y == _y) {
    		return true;
    	}
        return false;
    }
}
